package org.digitarts.rtms.spring.collectors.agent.jms;

import java.util.Set;

import javax.jms.JMSException;
import javax.jms.Message;
import javax.jms.MessageListener;
import javax.jms.TextMessage;

import org.digitarts.rtms.spring.collectors.shell.commands.Command;
import org.digitarts.rtms.spring.collectors.shell.commands.CommandSet;
import org.digitarts.rtms.tracing.ITracer;
import org.digitarts.rtms.tracing.Trace;
import org.digitarts.rtms.tracing.TracerFactory;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.factory.BeanFactoryAware;

public class JMSAgentResponseListener implements BeanFactoryAware, MessageListener
{
	protected BeanFactory	beanFactory	= null;
	protected ITracer		tracer		= TracerFactory.getInstance();

	public void setBeanFactory(BeanFactory beanFactory) throws BeansException
	{
		this.beanFactory = beanFactory;
	}

	public void onMessage(Message message)
	{
		if (message instanceof TextMessage)
		{
			try
			{
				TextMessage responseMessage = (TextMessage) message;
				String response = responseMessage.getText();
				String commandSetName = responseMessage.getStringProperty(JMSAgentConstants.COMMAND_SET_BEAN_NAME);
				String commandName = responseMessage.getStringProperty(JMSAgentConstants.COMMAND_SET_COMMAND_NAME);
				String[] tracingNameSpace = responseMessage.getStringProperty(JMSAgentConstants.TRACING_NAMESPACE).split(JMSAgentConstants.TRACING_NAMESPACE_DELIM);
				// String tmpName =
				// responseMessage.getStringProperty(JMSAgentConstants.TRACING_NAMESPACE);
				// System.out.println("Received Messsage from:[" + tmpName +
				// "]");
				CommandSet commandSet = (CommandSet) beanFactory.getBean(commandSetName);

				Command command = commandSet.getCommand(commandName);

				Set<Trace> traces = command.processResult(response);
				for (Trace t : traces)
				{
					t.trace(tracer, tracingNameSpace);
				}

			}
			catch (JMSException ex)
			{
				throw new RuntimeException(ex);
			}
		}
		else
		{
			throw new IllegalArgumentException("Message must be of type TextMessage");
		}
	}

}
